#include <xscript/xscriptexecutor.h>
#include <xscript/xitemfloat.h>
#include <xscript/xitemint32.h>
#include <xscript/xitemstring.h>
#include <astree/xabstractsyntaxtreearithmetic.h>

bool XAbstractSyntaxTreePlus::invokeImpl(std::shared_ptr<XVariableTable> table) {
    auto ok = getChildAt(0)->invoke(table);
    if (!ok)
        return false;

    ok = getChildAt(1)->invoke(table);
    if (!ok)
        return false;

    auto a = getChildAt(0)->getResult();
    auto b = getChildAt(1)->getResult();

    if (a->asString() && b->asString()) {
        result = std::make_shared<XItemString>(a->asString()->getValue() + b->asString()->getValue());
        return true;
    }

    if (!b->isNumber()) {
        XScriptExecutor::getInstance()->setError(XError::XError_ArgumentCountError, getChildAt(1)->getToken()->toString());
        return false;
    }

    if (a->asInt32()) {
        int32_t value = a->asInt32()->getValue();
        value = plus<int32_t>(value, b);
        result = std::make_shared<XItemInt32>(value);
        return true;
    } else if (a->asFloat()) {
        float value = a->asFloat()->getValue();
        value = plus(value, b);
        result = std::make_shared<XItemFloat>(value);
        return true;
    }
    XScriptExecutor::getInstance()->setError(XError::XError_ArgumentCountError, getChildAt(0)->getToken()->toString());
    return false;
}
